import json

import paho.mqtt.client as mqtt
import time
from aesEnDecryptions.aesEnDecryption import aes_decrypt_b64, aes_encrypt_b64
from mqtt.iMqttClient import IMqttClient
from objects import globalVariable

# MQTT客户端回调API版本
callback_api_version = mqtt.MQTTv311  # 使用MQTT 3.1.1协议

class MqttClient(IMqttClient):
    def __init__(self, client_id, user_name, pass_word, topics, will_topic, will_message):
        self.topics = topics
        self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1, client_id)
        self.client.username_pw_set(user_name, pass_word)
        self.client.will_set(will_topic, will_message, qos=1, retain=True)
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.on_disconnect = self.on_disconnect
        self.connected = False

    def get_mqtt_client(self):
        global mqtt_client
        """
        获取全局 MQTT 客户端实例
        """
        if self.client is not None:
            mqtt_client = self.client
        else:
            raise ValueError("MQTT Client not initialized. Call init_mqtt_client() first.")
        return mqtt_client

    def connect(self, host, port, keepalive=60):
        self.client.connect(host, port, keepalive)
        self.client.loop_start()
        while not self.connected:
            time.sleep(0.1)  # 等待直到连接成功

    def disconnect(self):
        self.client.loop_stop()
        self.client.disconnect()

    def subscribe(self, topic, qos=0):
        self.client.subscribe(topic, qos)

    def publish(self, topic, message, qos=0):
        self.client.publish(topic, message, qos)

    def on_connect(self, client, userdata, flags, rc, properties=None):
        if rc == 0:
            client_no_send = 'automaticlogonzfh1'
            org_id = '8'
            type_id= '17'
            version = '2.0.45'
            online = '{clientNo:"%s",orgId:"%s",type:"%s",version:"%s",msg:"1"}' % (
            client_no_send, org_id, type_id, version)
            key = 'keson-123abcdefg'.encode('utf-8')
            # 铭文加密函数初始化
            online_message_encrypted = aes_encrypt_b64(online, key)
            self.publish('online', online_message_encrypted,1)
            print("Connected to MQTT Broker!")
            self.connected = True
            for topic in self.topics:
                self.subscribe(topic)
        else:
            print(f"Failed to connect, return code {rc}\n")
            self.reconnect()

    def on_message(self, client, userdata, msg):
        globalVariable.offline_flag = False
        key = 'keson-123abcdefg'.encode('utf-8')
        payload_str = aes_decrypt_b64(msg.payload, key)
        try:
            json_object = json.loads(payload_str)
            print(f'接收平台json:{json_object}')
            if msg.topic in self.topics[0]:
                todo = json_object['todo']


        except json.JSONDecodeError as e:
            print(f"JSON 解析错误: {e}")
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")

    def on_disconnect(self, client, userdata, rc):
        print("Disconnected from MQTT Broker")
        self.connected = False
        self.reconnect()

    def reconnect(self):
        # 尝试重新连接的逻辑
        print("Attempting to reconnect...")
        self.client.reconnect()
